/*
 * @Author: wangdazhuang
 * @Date: 2024-10-19 09:54:20
 * @LastEditTime: 2025-02-18 14:19:49
 * @LastEditors: wangdazhuang
 * @Description: 
 * @FilePath: /pornhub_app/lib/http/http_exception_handler.dart
 */
import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:pornhub_app/http/http_const.dart';

import '../utils/logger.dart';
import 'base_repsponse_model.dart';
import 'http_special_code_handler.dart';

/// catch到的exception处理
abstract class HttpExceptionHandler {
  static void handleException(DioException e) {
    _printError(e);
    final code = e.response?.statusCode ?? 200;
    final response = e.response;
    if (response == null || response.data == null) {
      throw BaseRespModel.fromJson(
        {'code': code, "msg": e.message ?? ''},
      );
    }
    final data = response.data!;
    if (data is BaseRespModel == false) {
      throw BaseRespModel.fromJson(
        {'code': code, "msg": e.message ?? '', "data": data},
      );
    }

    ///处理特殊业务码
    if (HttpConst.specialCodeList.contains(code)) {
      HttpSpecialCodeHandler.doAction(response);
    }

    ///data是baseRespModel
    throw data;
  }

  ///错误打印
  static void _printError(DioException e) {
    if (e.response == null) {
      logger.d(e);
      return;
    }
    final response = e.response!;
    final pathQuery = <String>[];
    pathQuery.add(response.realUri.path);
    if (response.realUri.hasQuery) {
      pathQuery.add(response.realUri.query);
    }
    final code = response.statusCode ?? 200;
    var json = response.data;
    var msg = '';
    if (json is BaseRespModel) {
      json = json.toJson();
      msg = json.msg ?? '';
    } else if (json is Map) {
      msg = json["msg"] ?? '';
    } else {
      msg = e.message ?? '';
    }
    if (msg.isNotEmpty) {
      SmartDialog.showToast(msg, alignment: Alignment.center);
    }
    logger.d(
        "${pathQuery.join('?')}>>>>statusCode>>>>$code>>>businessError>>${response.requestOptions.data}\n${const JsonEncoder.withIndent('  ').convert(json)}");
  }
}
